//
//  AECommunityDetailHeaderView.m
//  AESOLAR_IOS
//
//  Created by Bin Tang on 2024/10/20.
//  Copyright © 2024 Mr.Wang. All rights reserved.
//

#import "AECommunityDetailHeaderView.h"
#import "AECommunityDetailModel.h"
#import "TYZControl.h"
#import "AENewsInfoModel.h"
#import <YYWebImage/CALayer+YYWebImage.h>
//#import <CALayer+YYWebImage.h>
#import "AECommunityDetailViewModel.h"
#import <WebKit/WebKit.h>

@interface AECommunityDetailHeaderView () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>

@property (nonatomic, strong) AECommunityDetailViewModel *viewModel;

@property (nonatomic, strong) AENewsInfoModel *model;

@property (nonatomic, strong) UILabel *titleLabel;

/// 日期图标
@property (nonatomic, strong) UIImageView *dateTagImgView;

/// 时间
@property (nonatomic, strong) UILabel *datetimeLabel;

/// 图片数组
@property (nonatomic, strong) NSArray *picViews;

@property (nonatomic,strong, nullable) UIView *lastView;


@property (nonatomic, strong) WKWebView  *webView;


/// 评论
@property (nonatomic, strong) TYZImageTitleButton *commentView;

/// 点赞
@property (nonatomic, strong) TYZImageTitleButton *praiseView;


/// 评论
- (void)initWithCommentView;

/// 点赞
- (void)initWithPraiseView;

@end

@implementation AECommunityDetailHeaderView

- (void)initWithSubView {
    [super initWithSubView];
    
    self.backgroundColor = [UIColor whiteColor];
}

- (void)initWithTitleLabel {
    if (!_titleLabel) {
        CGRect frame = CGRectMake(15, 7, self.width - 15 * 2, self.model.newsContentHeight);
        _titleLabel = [UILabel createWithLabel:self frame:frame font:self.model.newsContentFont propertiesBlock:^(UILabel * _Nonnull label) {
            label.textColor = [UIColor colorWithHexString:@"#3D444D"];
            label.numberOfLines = 0;
        }];
    }
    if (self.model) {
        self.titleLabel.height = self.model.newsTitleHeight;
        self.titleLabel.font = self.model.newsTitleFont;
        self.titleLabel.text = self.model.newsTitle;
//        [self.titleLabel sizeToFit];
    }
}

/// 日期图标
- (void)initWithDateTagImgView {
    if (!_dateTagImgView) {
        UIImage *image = [UIImage imageNamed:@"ic_main_date_tag"];
        CGRect frame = CGRectMake(15, _titleLabel.bottom + 7, image.size.width, image.size.height);
        _dateTagImgView = [UIImageView createWithImageView:self frame:frame defaultImage:image propertiesBlock:^(UIImageView * _Nonnull imageView) {
            
        }];
    }
}

/// 时间
- (void)initWithDatetimeLabel {
    if (!_datetimeLabel) {
        CGRect frame = CGRectMake(self.dateTagImgView.right + 4, 0, kScreenW - self.dateTagImgView.right - 4 - 20, 16);
        _datetimeLabel = [UILabel createWithLabel:self frame:frame font:[UIFont systemFontOfSize:12 weight:UIFontWeightRegular] propertiesBlock:^(UILabel * _Nonnull label) {
            label.textColor = [UIColor colorWithHexString:@"#8C9197"];
//            label.text = @"2024-10-12 23:34:23";
        }];
        _datetimeLabel.centerY = self.dateTagImgView.centerY;
    }
    if (self.model) {
        self.datetimeLabel.font = self.model.newsDataTimeFont;
        self.datetimeLabel.text = self.model.newsDataTime;
    }
}

- (void)initWithImages {
    CGSize picSize = CGSizeMake(self.model.imageWidth, self.model.imageHeight);
    CGFloat top = self.datetimeLabel.bottom + 12;
    if (!_picViews)
    {
        NSMutableArray *picViews = [NSMutableArray new];
        @weakify(self);
        for (int i=0; i<9; i++)
        {
            TYZControl *imageView = [TYZControl new];
//            imageView.size = CGSizeMake(self.model.imageWidth, self.model.imageHeight);
            imageView.size = CGSizeMake(picSize.width, picSize.height);
            imageView.hidden = YES;
            imageView.clipsToBounds = YES;
            imageView.backgroundColor = [UIColor colorWithHexString:@"#f0f0f0"];
            imageView.exclusiveTouch = YES;
            
            __weak typeof(imageView)weakS = imageView;
            imageView.touchBlock = ^(TYZControl * _Nonnull view, YYGestureRecognizerState state, NSSet * _Nonnull touches, UIEvent * _Nonnull event) {
                @strongify(self);
                if (state == YYGestureRecognizerStateEnded)
                {
                    UITouch *touch = touches.anyObject;
                    CGPoint point = [touch locationInView:view];
                    if (CGRectContainsPoint(view.bounds, point))
                    {
                        if (self.touchImageViewBlock)
                        {
                            self.touchImageViewBlock(i, weakS);
                        }
                    }
                }
                
            };
            
            [picViews addObject:imageView];
            [self addSubview:imageView];
        }
        _picViews = picViews;
    }
    
    self.lastView = nil;
    if (self.model == nil) {
        return;
    }
    
    int picsCount = (int)self.model.ossUrls.count; // 图片张数
    CGRect frame = CGRectZero;
    for (int i=0; i<9; i++)
    {
        UIView *imageView = _picViews[i];
        if (i >= picsCount)
        {
            [imageView.layer yy_cancelCurrentImageRequest];
            imageView.hidden = YES;
        }
        else
        {
            CGPoint origin = {0};
            float left = 15;
            switch (picsCount)
            {
                case 1:
                {
                    origin.x = left;
                    origin.y = top;
                } break;
                case 4:
                {
                    origin.x = left + (i % 3) * (picSize.width + 3);
                    origin.y = top + (int)(i / 3) * (picSize.height + 3);
                } break;
                default:
                {
                    origin.x = left + (i % 3) * (picSize.width + 3);
                    origin.y = top + (int)(i / 3) * (picSize.height + 3);
                } break;
            }
            
            frame = (CGRect){.origin = origin, .size = picSize};
            imageView.frame = frame;
            imageView.hidden = NO;
            [imageView.layer removeAnimationForKey:@"contents"];
            self.lastView = imageView;
            NSString *imageUrl = [self.model.ossUrls objectOrNilAtIndex:i];
            @weakify(imageView);
            [imageView.layer yy_setImageWithURL:[NSURL URLWithString:imageUrl] placeholder:nil options:YYWebImageOptionAvoidSetImage completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                @strongify(imageView);
                
                if (!imageView)
                {
                    return;
                }
                
                if (image && stage == YYWebImageStageFinished)
                {
                    int width = image.size.width;
                    int height = image.size.height;
                    CGFloat scale = (height / width) / (imageView.height / imageView.width);
                    if (scale < 0.99 || isnan(scale))
                    {// 宽图把左右两边裁掉
                        imageView.contentMode = UIViewContentModeScaleAspectFill;
                        imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
                    }
                    else
                    {// 高图只保留顶部
                        imageView.contentMode = UIViewContentModeScaleToFill;
                        imageView.layer.contentsRect = CGRectMake(0, 0, 1, (float)width/height);
                    }
                    ((TYZControl *)imageView).image = image;
                    if (from != YYWebImageFromMemoryCacheFast)
                    {
                        CATransition *transition = [CATransition animation];
                        transition.duration = 0.15;
                        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                        transition.type = kCATransitionFade;
                        [imageView.layer addAnimation:transition forKey:@"contents"];
                    }
                }
            }];
            
        }
    }
}


- (void)initWithWebView
{
    if (!_webView)
    {
//        CGSize size = [UIScreen mainScreen].bounds.size;
        CGRect frame = CGRectMake(0, self.lastView.bottom + 12, self.width, 0);
        WKWebViewConfiguration *config = [WKWebViewConfiguration new];
        config.userContentController = [ self wkwebViewScalPreferences];
        //初始化偏好设置属性：preferences
        config.preferences = [WKPreferences new];
        //The minimum font size in points default is 0;
        config.preferences.minimumFontSize = 10;
        //是否支持JavaScript
        config.preferences.javaScriptEnabled = YES;
        
        //不通过用户交互，是否可以打开窗口
        //        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        
        _webView = [[WKWebView alloc]initWithFrame:frame configuration:config];
        
        // 这行代码可以是侧滑返回webView的上一级，而不是根控制器（*只针对侧滑有效）
        [_webView setAllowsBackForwardNavigationGestures:true];
        
        
//        webView.customUserAgent = "Mozilla/5.0 (iPhone; iOS 17.0; en-US) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/16G78 Safari/604.1"
        _webView.customUserAgent = @"Mozilla/5.0 (iPhone; iOS 17.0; en-US) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/16G78 Safari/604.1";
        
        
        _webView.UIDelegate = self; // UI 代理
//        _webView.scrollView.scrollEnabled = YES;
        _webView.navigationDelegate = self; // 导航代理
        
        _webView.scrollView.scrollEnabled = NO;
        [self addSubview:_webView];
    }
    [_webView loadHTMLString:self.model.newsContent baseURL:[NSURL URLWithString:kBaseUrl]];
    // http://111.39.245.157:8087/mobile/question.html
//    NSURL *url = [NSURL URLWithString:_urlStr];
//    debugLog(@"url=%@", _url);
//    if (_url && ![_url isEqual:[NSNull null]] && _url.absoluteString && ![objectNull(_url.absoluteString) isEqualToString:@""])
//    {
////        [self.webView loadRequest:[NSURLRequest requestWithURL:_url]];
//        [self loadWebView];
//    }
}


/// 评论
- (void)initWithCommentView:(float)webHeight {
    if (!_commentView) {
        CGRect frame = CGRectMake(15, self.lastView.bottom + webHeight + 12, 0, 22);
        _commentView = [TYZImageTitleButton createWithImageButton:self frame:frame font:[UIFont systemFontOfSize:15 weight:UIFontWeightBold] target:self action:nil propertiesBlock:^(TYZImageTitleButton * _Nonnull button) {
            [button setTitleColor:[UIColor colorWithHexString:@"#3D444D"] forState:UIControlStateNormal];
        }];
    }
    if (self.model) {
        NSString *str = [NSString stringWithFormat:@"评论 %zd", self.model.newsCommentsCount];
        float width = [str widthForFont:self.commentView.titleLabel.font];
        if (self.model.ossUrls.count > 0) {
            self.commentView.top = self.lastView.bottom + webHeight + 12;
        } else {
            self.commentView.top = self.datetimeLabel.bottom + webHeight + 12;
        }
        
        self.commentView.width = width;
        [self.commentView setTitle:str forState:UIControlStateNormal];
    }
}

#pragma mark - 大小适应
- (WKUserContentController *)wkwebViewScalPreferences
{
    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    
    return wkUController;
}


/// 点赞
- (void)initWithPraiseView:(float)webHeight {
    UIFont *font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
    UIImage *image = [UIImage imageNamed:@"ic_main_praise_nor"];
    UIImage *imageSel = [UIImage imageNamed:@"ic_main_praise_sel"];
    if (!_praiseView) {
        NSString *str = @"赞 0";
        float width = [str widthForFont:font] + 10 + image.size.width;
        CGRect frame = CGRectMake(0, self.lastView.bottom + webHeight + 12, width, 22);
        _praiseView = [TYZImageTitleButton createWithImageButton:self frame:frame font:font target:self action:@selector(actionWithPraise:) propertiesBlock:^(TYZImageTitleButton * _Nonnull button) {
            [button setTitle:str forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithHexString:@"#3D444D"] forState:UIControlStateNormal];
            [button setImage:image forState:UIControlStateNormal];
            [button setImage:imageSel forState:UIControlStateSelected];
            [button layoutButtonWithEdgeInsetsStyle:TYZButtonEdgeInsetsStyleLeft imageTitleSpace:8];
        }];
    }
    if (self.model) {
        NSString *str = [NSString stringWithFormat:@"赞 %zd", self.model.newsLikes];
        float width = image.size.width + 6 + [str widthForFont:self.praiseView.titleLabel.font] + 2;
        self.praiseView.centerY = self.commentView.centerY;
        self.praiseView.width = width;
        self.praiseView.left = self.width - width - 15;
        [self.praiseView setTitle:str forState:UIControlStateNormal];
        [self.praiseView layoutButtonWithEdgeInsetsStyle:TYZButtonEdgeInsetsStyleLeft imageTitleSpace:5];
        self.praiseView.selected = self.model.like;
        
//        self.praiseView.backgroundColor = [UIColor orangeColor];
    }
}






#pragma mark - WKUIDelegate 主要处理JS脚本，确认框，警告框等。因此WKNavigationDelegate更加常用。




// 页面时弹出窗口 _blank处理
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

/// 返回高度
/// - Parameter height: height description
- (void)webViewResultHeight:(float)height {
//    NSLog(@"height=%f", height);
    self.webView.height = height;
    
    /// 评论
    [self initWithCommentView:height];

    /// 点赞
    [self initWithPraiseView:height];

    
    self.height = self.height + height + 12;
    
}

#pragma mark - WKNavigationDelegate 主要处理一些跳转、加载处理操作

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation
{
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    float height = webView.scrollView.contentSize.height;
    self.webView.height = height;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self webViewResultHeight: height];
//    });
    
    __weak typeof(self)weakSelf = self;
//    [self.webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//        NSString *title = response;
//        if (![objectNull(title) isEqualToString:@""])
//        {
////                weakSelf.navigationItem.title = title;
//        }
//    }];
    
    [self.webView evaluateJavaScript:@"document.body.scrollHeight;" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        float height = [response floatValue];
        [weakSelf webViewResultHeight: height];
    }];
    
//    func getWebViewContentHeight() {
//        let jsCode = "document.body.scrollHeight;"
//        webView.evaluateJavaScript(jsCode) { (result, error) in
//            if let height = result as? CGFloat {
//                print("Content height from JS: \(height)")
//            } else {
//                print("Error getting height: \(String(describing: error))")
//            }
//        }
//    }

}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error
{
    
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if (message.name)
    {
        NSLog(@"OC 层面的消息");
    }
    NSLog(@"message == %@ --- %@", message.name, message.body);
}

/// 点赞
/// - Parameter sender: sender description
- (void)actionWithPraise:(id)sender {
    if (self.touchPraiseBlock) {
        self.touchPraiseBlock();
    }
}


- (void)updateWithViewData:(id)data {
    self.viewModel = data;
    self.model = self.viewModel.newsInfoModel;
    
    
    [self initWithTitleLabel];
//    
    [self initWithDateTagImgView];
//    
    [self initWithDatetimeLabel];
//    
    [self initWithImages];
    
    [self initWithWebView];
    
//    /// 评论
//    [self initWithCommentView];
//
//    /// 点赞
//    [self initWithPraiseView];

}

@end
